<?php
namespace app\api\controller;

use think\Controller;
use think\Config;
use think\Validate;
use think\Request;
use app\api\model\User;
use app\api\model\UserAuth;
use app\api\model\Third;
use app\api\model\UserInfo;


class Api extends Controller
{
    public function index()
    {
        $aa = genToken();
        return $aa;
    }

    /**
	 * 根据登录时传来的code获取 openid，session_key，unionid
	 * @param string $code 请求传来的code
	 */
    public function get_weixin_login($code='')
    {
    	if(trim(empty($code))){

    		return error("Code can't be empty");
    	}

    	$apiurl = 'https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code';
		header("Content-type:text/html;charset=utf-8;");
		$appid = Config::get('weixin.appid');
		$secret = Config::get('weixin.secret');
		$url = str_replace("JSCODE",$code,str_replace("APPID",$appid,str_replace("SECRET",$secret,$apiurl)));
		$res = json_decode(file_get_contents($url), true);

		if(empty($res['openid'])){
			return error('获取失败，请重新获取');
		}

        return success($res, '获取成功');

        // $validate = new Validate(
        //     [
        //         ['nickName','require','昵称不能为空'],
        //         ['avatarUrl','require','头像不能为空'],
        //         ['gender','require','性别不能为空'],
        //     ]
        // );
        // $data = $this->request->param();
        // if (!$validate->check($data)) {
        //     return error($validate->getError());
        // }

        // //检查当前用户是否第一次尽进来
        // $user_info = User::where('wechat_openid', $res['openid'])->find();
        // if(!empty($user_info)){ //用户存在做更新操作
        //     // dump($data);exit;
        //     $user_info_data = array(
        //         'nickname' => $data['nickName'],
        //         'sex' => $data['gender'],
        //     );
        //     $third_data = array(
        //         'nick' => $data['nickName'],
        //         'avatar' => $data['avatarUrl'],
        //         'gender' => $data['gender'] == 1 ? 'm' : 'f',
        //     );
        //     //更新users表
        //     UserInfo::where('user_id', $user_info['user_id'])->update($user_info_data);
        //     Third::where('openid', $user_info['wechat_openid'])->update($third_data);

        //     $res = array(
        //         'token' => $user_info['token'],
        //         'user_id' => $user_info['user_id'],
        //     );

        //     return success($res, '登录成功');

        // } else{ //不存在，添加新的用户
            
        //     //添加到users表
        //     $user = new User;
        //     $user->wechat_openid = $res['openid'];
        //     $user->session_key = $res['session_key'];
        //     $user->password = MD5(Config::get('web.password'));    //默认密码
        //     $user->token = genToken();
        //     $user->save();

        //     //添加到第三方用户表jk_user_third
        //     $third = Third::create([
        //         'openid' => $user->wechat_openid,
        //         'channel' =>'weixin',
        //         'nick' => $data['nickName'],
        //         'avatar' => $data['avatarUrl'],
        //         'gender' => $data['gender'] == 1 ? 'm' : 'f',
        //     ]);

        //     //认证信息
        //     $auth = UserAuth::create([
        //         'user_id' =>  $user->user_id,
        //     ]);

        //     //添加到jk_user_informations表
        //     $user_info = UserInfo::create([
        //         'user_id' => $user->user_id,
        //         'nickname' => $data['nickName'],
        //         'create_at' => time(),
        //         'sex' => $data['gender'],
        //         'pid' => 0,
        //         'unicode_id' => sha1(md5(time().$user->user_id))    //唯一身份id
        //     ]);

        //     if(empty($user) || empty($third) || empty($auth) || empty($user_info)){

        //         return error('授权失败，请重新授权');
        //     }
        //     add_signin(2, 1, Config::get('web.integral'), $user->user_id, '新用户注册(小程序注册入口)');

        //     $res = array(
        //         'token' => $user->token,
        //         'user_id' => $user->user_id,
        //     );

        //     return success($res, '登录成功');
        // }

		// return success($res, '获取成功');
    }

     /**
	 * 获取用户的信息并且保存/更新  暂时弃用
	 */
    public function save()
    {
        $request = Request::instance();
        $ip = $request->ip();
    	$validate = new Validate(
            [
                ['openid','require','openid不能为空'],
                ['session_key','require','session_key不能为空'],
                ['nickName','require','昵称不能为空'],
                ['avatarUrl','require','头像不能为空'],
                ['gender','require','性别不能为空'],
            ]
        );
        $data = $this->request->param();
        if (!$validate->check($data)) {
            return error($validate->getError());
        }

        //检查当前用户是否第一次尽进来
        $user_info = User::where('wechat_openid', $data['openid'])->find();
        if(!empty($user_info)){ //用户存在做更新操作
            // dump($data);exit;
            $user_info_data = array(
                'nickname' => $data['nickName'],
                'sex' => $data['gender'],
            );
            $third_data = array(
                'nick' => $data['nickName'],
                'avatar' => $data['avatarUrl'],
                'gender' => $data['gender'] == 1 ? 'm' : 'f',
            );
            //更新users表
            UserInfo::where('user_id', $user_info['user_id'])->update($user_info_data);
            Third::where('openid', $user_info['wechat_openid'])->update($third_data);

            //登录记录
            $login_log = array(
                'user_id' => $user_info['user_id'],
                'login_ip' => $ip,
                'create_at' => time()
            );

            \think\Db::table('jk_loginrecordings')->insert($login_log);

            $res = array(
                'token' => $user_info['token'],
                'user_id' => $user_info['user_id'],
            );

            return success($res, '登录成功');

        } else{ //不存在，添加新的用户
            
            //添加到users表
            $user = new User;
            $user->wechat_openid = $data['openid'];
            $user->session_key = $data['session_key'];
            $user->password = MD5(Config::get('web.password'));    //默认密码
            $user->token = genToken();
            $user->save();

            //添加到第三方用户表jk_user_third
            $third = Third::create([
                'openid' => $user->wechat_openid,
                'channel' =>'weixin',
                'nick' => $data['nickName'],
                'avatar' => $data['avatarUrl'],
                'gender' => $data['gender'] == 1 ? 'm' : 'f',
            ]);

            //认证信息
            $auth = UserAuth::create([
                'user_id' =>  $user->user_id,
            ]);

            //添加到jk_user_informations表
            $user_info = UserInfo::create([
                'user_id' => $user->user_id,
                'nickname' => $data['nickName'],
                'create_at' => time(),
                'sex' => $data['gender'],
                'pid' => 0,
                'unicode_id' => sha1(md5(time().$user->user_id))    //唯一身份id
            ]);

            if(empty($user) || empty($third) || empty($auth) || empty($user_info)){

                return error('授权失败，请重新授权');
            }
            add_signin(2, 1, Config::get('web.integral'), $user->user_id, '新用户注册(小程序注册入口)');

            //登录记录
            $login_log = array(
                'user_id' => $user_info['user_id'],
                'login_ip' => $ip,
                'create_at' => time()
            );
            \think\Db::table('jk_loginrecordings')->insert($login_log);

            $res = array(
                'token' => $user->token,
                'user_id' => $user->user_id,
            );

            return success($res, '登录成功');
        }
    }



     /**
     * 上传单图片
     *  图片名称：file
     */
    public function uploadfile()
    {
        $file_type = $this->request()->param()['file_type'];
        switch ($file_type)
        {
            case 1:
                $url = 'adv';//广告
                break;
            case 2:
                $url = 'authentications';//认证
                break;
            case 3:
                $url = 'level_pic';//会员等级
                break;
            case 4:
                $url = 'nav';//导航
                break;
            case 5:
                $url = 'orders';//交易
                break;
            case 6:
                $url = 'portrait';//头像
                break;
            case 7:
                $url = 'prove';//收款凭证
                break;
            case 8:
                $url = 'system';//系统
                break;
            case 9:
                $url = 'tool_templates';//工具模板
                break;
            case 10:
                $url = 'wang';//wang编辑器
                break;
            case 11:
                $url = 'weixin_code';//微信
                break;
            default:
                return error('图片路径错误');
        }

        $file = request()->file('file');
        if ($file) {
            $info = $file->validate(['size'=>15678000,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $url );
            if($info){
                $pathinfo = pathinfo($info->getSaveName());
                $pic_url = $info->getSaveName();
                $res['savename'] = $pic_url;
                
                return success($res, '图片上传成功');
            } else{
                
                return error($file->getError());
            }
        } else{

            return error('请上传图片');
        }
    }

}
